<template>
    <div>
        <el-dialog @close="close(ruleFormRef)" center v-model="info.isShow" :title="info.isAdd ? '添加角色' : '修改角色'">
            <el-form ref="ruleFormRef" :rules="rules" :model="role">
                <el-form-item label="角色名称" prop="rolename" :label-width="formLabelWidth">
                    <el-input v-model="role.rolename" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色菜单" :label-width="formLabelWidth">
                    <!-- 树形控件 -->
                    <el-tree check-strictly accordion ref="treeRef" :data="menuList" show-checkbox default-expand-all
                        node-key="id" highlight-current :props="{
                            children: 'children',
                            label: 'title',
                        }" />
                </el-form-item>

                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="role.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="close(ruleFormRef)">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef, info.isAdd)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, defineProps, defineEmits, computed, defineExpose } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElTree } from 'element-plus'
// 弹窗
import { ElMessage } from 'element-plus'
// 引入接口
import { roleAdd, roleInfo, roleEdit } from '@/request/app'
// 引入仓库
import { useStore } from 'vuex'
const store = useStore()
const treeRef = ref<InstanceType<typeof ElTree>>()
const ruleFormRef = ref<FormInstance>()
const formLabelWidth = '140px'
// 接收父组件传递的参数，控制弹窗显示隐藏以及标题的更换
defineProps(['info'])
// 获取仓库中的菜单列表,渲染弹窗的树形结构
let menuList = computed(() => store.getters['menu/getMenuList'])
let getMenuList = () => {
    // 若是从菜单管理点击过来的，菜单列表已经调用过有数据了，在这里就不再调用了
    // 如果菜单列表没有内容就在这里调用接口
    if (menuList.value.length == 0) {
        store.dispatch('menu/getMenuListAction')
    }
}
getMenuList()
// 表单数据
const role = ref({
    rolename: '',
    menus: '',
    status: 1
})
// 接收id，做编辑准备
let newid = 0
// 验证条件
const rules = reactive<FormRules>({
    rolename: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
    ],
})
// 置空
const reset = () => {
    role.value = {
        rolename: '',
        menus: '',
        status: 1
    },
        // 清空树节点选中状态
        treeRef.value!.setCheckedNodes([])
}
// 传递给父组件 设置的自定义事件名
let emit = defineEmits(['close'])
//取消按钮事件
let close = (formEl: FormInstance | undefined) => {
    // 传递取消事件关闭弹窗
    emit('close', false)
    // 清空表单
    reset()
    if (!formEl) return
    formEl.resetFields()
}
// 回显
let lookup = (id: number) => {
    console.log(id, 'idididid');
    newid = id
    // 调用查询数据接口
    roleInfo({ id })
        .then((res: any) => {
            console.log(res, '一条数据');
            role.value = res.list
            treeRef.value!.setCheckedKeys(role.value.menus ? role.value.menus.split(',') : [])
        })
}
// 暴露子组件回显方法
defineExpose({
    lookup
})
// 确认事件
const submitForm = async (formEl: FormInstance | undefined, isAdd: any) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(role.value, '表单')
            console.log(treeRef.value!.getCheckedKeys(false), '树形结构')
            role.value.menus = treeRef.value!.getCheckedKeys() ? treeRef.value!.getCheckedKeys().join(',') : ''
            if (isAdd) {
                // 添加接口
                roleAdd(role.value)
                    .then(res => {
                        console.log(res, '角色添加');
                        if (res.code == 200) {
                            // 提示
                            ElMessage.success(res.msg)
                            // 关闭弹窗
                            close(formEl)
                            // 重新调用列表
                            store.dispatch('role/getRoleListAction')
                        } else {
                            // 提示
                            ElMessage.error(res.msg)
                        }
                    })
            } else {
                //编辑接口
                roleEdit({
                    ...role.value,
                    id: newid
                })
                    .then((res: any) => {
                        console.log(res, '编辑');
                        if (res.code == 200) {
                            ElMessage.success(res.msg)
                            // 关闭弹窗
                            close(formEl)
                            // 重新调用列表
                            store.dispatch('role/getRoleListAction')
                        } else {
                            ElMessage.error(res.msg)
                        }
                    })
            }
            // 清空验证
            formEl.resetFields()
        } else {
            console.log('error submit!', fields)
        }
    })
}

</script>

<style  lang="" scoped>

</style>
